﻿using YoUI.Core;
using DG.Tweening;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace YoUI.Core.UIAnima
{
    [RequireComponent(typeof(RectTransform))]
    public abstract class YoTweenBase : MonoBehaviour
    {
        // 动画播放的方向
        private bool _PlayDirectory = true;

        // 当前UI
        protected RectTransform rt;

        // 动画对象
        protected Tweener tweener;

        [Header("In/Out")]
        public Ease _InEase = Ease.Linear;
        public Ease _OutEase = Ease.Linear;

        // 动画完成时间
        public float duration;
        // 循环次数
        public int _LoopCount = 1;
        // 循环类型
        public LoopType _LoopType;

        /// <summary>
        /// 基本初始化
        /// </summary>
        protected virtual void Awake()
        {
            rt = GetComponent<RectTransform>();
            var ui = GetComponent<YoBase>();
            
            if (ui != null)
            {

                // 绑定显示事件
                ui.OnShow += ShowAndHide;

                // 绑定隐藏事件
                ui.OnHide += ShowAndHide;
            }
        }

        protected virtual void Start()
        {
                
        }

        /// 显示还是隐藏时，播放UI动画
        public void ShowAndHide(YoBase ui)
        {
            
            if (tweener == null)
            {
                tweener = Anima();
                ui.gameObject.SetActive(true);
                // 播放时调用
                tweener.OnPlay(() =>
                {
                    // false 就播放显示的动画
                    if(!ui.gameObject.activeInHierarchy)
                        ui.gameObject.SetActive(true);
                });

                // 绑定播放完成后 暂停的回调
                tweener.OnPause(() =>
                {
                    if (!_PlayDirectory)
                    {
                        ui.gameObject.SetActive(false);
                    }
                });

                SetConfig(tweener);
            }
            else
            {
                Play();
            }
        }

        /// 设置
        public void SetConfig(Tweener tw)
        {
            tw.SetLoops(_LoopCount, _LoopType);
            tw.SetEase(_InEase);
            tw.SetAutoKill(false);
        }
        /// <summary>
        /// 播放
        /// </summary>
        public virtual void Play()
        {
            if (_PlayDirectory)
            {
                tweener.PlayBackwards();
            }
            else
            {
                tweener.PlayForward();
            }

            // 更新方向
            _PlayDirectory = !_PlayDirectory;
        }

        public abstract Tweener Anima();
    }
}
